<template>
  <div class="TaskPanel">
    <div>
      <img src="@/assets/img/other/icon-任务看板.png" class="TaskPanel-title-img" />
      <span class="TaskPanel-title-name">任务看板</span>
    </div>
    <div class="line"></div>
    <div class="TaskPanel-option-one">
      <el-select v-model="classvalue" @change="GetClassValue(classvalue)" placeholder="暂无数据">
        <el-option v-for="(item, classindex) in State.trainingtaskarr" :key="classindex" :label="item.name"
          :value="classindex">{{ item.name }}</el-option>
      </el-select>
    </div>
    <div class="TaskPanel-option-two">
      <el-select v-model="simulationtasksvalue" placeholder="暂无数据"
        @change="GetSimulationTasksValue(simulationtasksvalue)">
        <el-option v-for="(item, taskindex) in State.SimulationTasksarr" :key="taskindex" :label="item.title"
          :value="taskindex">{{ item.title }}
        </el-option>
      </el-select>
    </div>
    <div class="TaskPanel-panel">
      <div>
        <span>任务状态</span><span>|</span><span>{{ (State.taskaInformation.taskState === 0 || State.taskaInformation.taskState)
          ? State.taskaInformation.taskState : "暂无数据" }}</span>
      </div>
      <div>
        <span>任务时长</span><span>|</span><span>{{ (State.taskaInformation.timeLong === 0 || State.taskaInformation.timeLong) ?
          State.taskaInformation.timeLong + "分钟" : "暂无数据" }}</span>
      </div>
      <div>
        <span>任务类型</span><span>|</span><span>{{ (State.taskaInformation.taskType === 0 || State.taskaInformation.taskType) ?
          State.taskaInformation.taskType : "暂无数据" }}</span>
      </div>
      <div>
        <span>创建时间</span><span>|</span><span>{{ (State.taskaInformation.creationTime === 0 ||
          State.taskaInformation.creationTime) ? dateFormat(State.taskaInformation.creationTime) : '暂无数据' }}</span>
      </div>
      <div>
        <span>完成率</span><span>|</span><span>{{ (State.taskaInformation.finish === 0 || State.taskaInformation.finish) ?
          numFilter(State.taskaInformation.finish) * 100 + "%" : '暂无数据' }}</span>
      </div>
      <div>
        <span>参与人数</span><span>|</span><span>{{ (State.taskaInformation.userCount === 0 || State.taskaInformation.userCount)
          ? State.taskaInformation.userCount : '暂无数据' }}</span>
      </div>
      <div>
        <span>未开始</span><span>|</span><span>{{ (State.taskaInformation.notUserCount === 0 ||
          State.taskaInformation.notUserCount) ? State.taskaInformation.notUserCount : '暂无数据' }}</span>
      </div>
      <div>
        <span>最高分</span><span>|</span><span>{{ (State.taskaInformation.topScore === 0 || State.taskaInformation.topScore) ?
          State.taskaInformation.topScore : '暂无数据' }}</span>
      </div>
      <div>
        <span>平均分</span><span>|</span><span>{{ (State.taskaInformation.averageScore === 0 ||
          State.taskaInformation.averageScore) ? State.taskaInformation.averageScore : '暂无数据' }}</span>
      </div>
      <div>
        <span>合格率</span><span>|</span><span>{{ (State.taskaInformation.pass === 0 || State.taskaInformation.pass) ?
          numFilter(State.taskaInformation.pass) * 100 + "%" : '暂无数据' }}</span>
      </div>
    </div>
    <div class="TaskPanel-button" v-if="State.role === '1'">
      <div @click="ReleaseDialog" v-if="State.taskaInformation.taskState === '未发布'" class="button-open">发布</div>
      <div @click="FinishDialog" v-if="State.taskaInformation.taskState === '进行中'" class="button-end">结束</div>
      <div @click="DeleteDialog" v-if="State.taskaInformation.taskState === '已结束'" class="button-end">删除</div>
    </div>
    <!-- 删除任务对话框 -->
    <DialogComponents :DialogComponent="DeleteDialogComponent" @click="DeleteSimulationTasks"></DialogComponents>
    <!-- 发布任务对话框 -->
    <DialogComponents :DialogComponent="ReleaseDialogComponent" @click="ReleaseSimulationTasks"></DialogComponents>
    <!-- 结束任务对话框 -->
    <DialogComponents :DialogComponent="FinishDialogComponent" @click="FinishSimulationTasks"></DialogComponents>
  </div>
</template>

<script>
import { defineComponent, onMounted, reactive, ref } from "vue";
import bus from "@/bus.js";
import { postData, numFilter } from "@/assets/js/pubilcs.js";
import DialogComponents from "@/components/compon/DialogComponents.vue";
export default defineComponent({
  name: "HomeTaskPanel",
  components: {
    DialogComponents
  },
  setup(props, ctx) {
    //储存第一个下拉框对象的值
    let State = reactive(
      {
        //第一个下拉框的信息
        trainingtaskarr: [],
        //第二个下拉框的信息
        SimulationTasksarr: [],
        //面板信息
        taskaInformation: {
        },
        //用于选择选择第二个下拉框获取的id值
        SimulationtaskId: '',
        //用于选择第二个下拉框的index值
        SimulationtaskOneIndex: 0,
        SimulationtaskTwoIndex: 0,
        role: sessionStorage.getItem("role")
      }
    )
    bus.$off('UpdateHomeTaskPanel')
    bus.$on('UpdateHomeTaskPanel', (data) => {
      if (data === 'Updates') {
        GetAppointProductTask()
      }
    })
    //第一个下拉框的绑定的值
    let classvalue = ref("")
    //第二个下拉框的绑定的实训任务的值
    let simulationtasksvalue = ref("")
    //获取所有任务
    function GetAppointProductTask() {
      let role = sessionStorage.getItem("role")
      let userid = sessionStorage.getItem("userid")
      let productId = sessionStorage.getItem("productId")
      if (role === "1") {
        postData("/api/CourseManage/GetCourseAndTrainingTask", JSON.stringify({ UserId: userid, productId: productId }), sessionStorage.getItem("token")).
          then(function (rep) {
            if (rep.success && rep.result.result) {
              //设置第一行的下拉框
              State.trainingtaskarr = rep.result.result
              //设置第一行的下拉框值
              classvalue.value = State.trainingtaskarr[0].name
              //设置第二行的下拉框
              State.SimulationTasksarr = State.trainingtaskarr[0].trainingTasks
              //对第二个下拉框的数据进行判断,如果有就设置标题,如果没有就设置暂无数据
              if (State.SimulationTasksarr.length !== 0) {
                //设置第二行的下拉框的值
                simulationtasksvalue.value = State.SimulationTasksarr[0].title
                //详细面板的信息
                GetSimulationTasksValue(0)
                //获取第二行下拉框的id(用于删除发布结束任务)
                State.SimulationtaskId = State.SimulationTasksarr[0].id
              } else {
                //设置第二行的下拉框的值
                simulationtasksvalue.value = "暂无数据"
                GetSimulationTasksValue(0)
              }
              //储存数据
              sessionStorage.setItem("AllSimulationTasks", JSON.stringify(State.trainingtaskarr))
            } else {
              State.trainingtaskarr = ''
              State.SimulationTasksarr = ''
              classvalue.value = "暂无数据"
              simulationtasksvalue.value = "暂无数据"
              GetSimulationTasksValue(0)
            }
          }).catch(error => {
            console.log(error)
          });
      } else if (role === "2") {
        postData("/api/TaskManage/GetCourseAndTrainingTask", JSON.stringify({ UserId: userid, productId: productId }), sessionStorage.getItem("token")).
          then(function (rep) {
            if (rep.success && rep.result.result.length !== 0) {
              //设置第一行的下拉框
              State.trainingtaskarr = rep.result.result
              //设置第一行的下拉框值
              classvalue.value = State.trainingtaskarr[0].name
              //设置第二行的下拉框
              State.SimulationTasksarr = State.trainingtaskarr[0].trainingTasks
              //对第二个下拉框的数据进行判断,如果有就设置标题,如果没有就设置暂无数据
              if (State.SimulationTasksarr.length !== 0) {
                //设置第二行的下拉框的值
                simulationtasksvalue.value = State.SimulationTasksarr[0].title
                //详细面板的信息
                GetSimulationTasksValue(0)
                //获取第二行下拉框的id(用于删除发布结束任务)
                State.SimulationtaskId = State.SimulationTasksarr[0].id
              } else {
                //设置第二行的下拉框的值
                simulationtasksvalue.value = "暂无数据"
                GetSimulationTasksValue(0)
              }
              //储存数据
              sessionStorage.setItem("AllSimulationTasks", JSON.stringify(State.trainingtaskarr))
            } else {
              State.trainingtaskarr = ''
              State.SimulationTasksarr = ''
              classvalue.value = "暂无数据"
              simulationtasksvalue.value = "暂无数据"
              GetSimulationTasksValue(0)
            }

          }).catch(error => {
            console.log(error)
          });
      }
    }
    //选中第一个下拉框执行的方法
    function GetClassValue(index) {
      // 第一个个下拉框的index值
      State.SimulationtaskOneIndex = index
      //选中第一个下拉框显示第二个下拉框的值
      State.SimulationTasksarr = State.trainingtaskarr[index].trainingTasks
      if (State.SimulationTasksarr.length === 0) {
        simulationtasksvalue.value = "暂无数据"
        //选取第一个的时候信息也要更新
        GetSimulationTasksValue(0)
      } else {
        //获取第二行下拉框的id(用于删除发布结束任务)
        State.SimulationtaskId = State.SimulationTasksarr[0].id
        //设置第二行的下拉框的值
        simulationtasksvalue.value = State.SimulationTasksarr[0].title
        //选取第一个的时候信息也要更新
        GetSimulationTasksValue(0)
      }
    }
    //选中第二个下拉框执行的方法
    function GetSimulationTasksValue(index) {
      //获取实训任务id
      if (State.SimulationTasksarr.length !== 0) {
        //实现任务的id
        let simulationtasksid = State.SimulationTasksarr[index].id
        // 第二个下拉框的index值
        State.SimulationtaskTwoIndex = index
        State.SimulationtaskId = simulationtasksid
        postData("/api/Statistical/GetKanbanByTrainingTaskId", JSON.stringify({ trainingTaskId: simulationtasksid }), sessionStorage.getItem("token")).
          then(function (rep) {
            if (rep.success) {
              //任务面板赋值
              State.taskaInformation = rep.result.result
              //准确率
              bus.$emit("ErrorPoint", State.taskaInformation)
              //难度
              bus.$emit("TaskEvaluation", State.taskaInformation)
              //成绩
              bus.$emit("ScoreInfo", State.taskaInformation.scoreInfo)
              //实训动态
              bus.$emit("stateModel", State.taskaInformation.stateModel)
              ctx.emit("LoadingPanel", "false")
            }
          }).catch(error => {
            console.log(error)
          });
      } else {
        //面板信息重置
        State.taskaInformation = {}
        //准确率
        bus.$emit("ErrorPoint", 'empty')
        //难度
        bus.$emit("TaskEvaluation", 'empty')
        //成绩
        bus.$emit("ScoreInfo", 'empty')
        //实训动态
        bus.$emit("stateModel", 'empty')
        ctx.emit("LoadingPanel", "false")
      }
    }
    //时间处理函数
    function dateFormat(dataStr) {
      let dateee = new Date(dataStr).toJSON();
      return new Date(+new Date(dateee) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')
    }
    //结束实训任务
    function FinishDialog() {
      FinishDialogComponent.Dialogboolean = true
    }
    //结束实训任务数据
    let FinishDialogComponent = reactive({
      Dialogboolean: false,
      Msg: "是否结束此实训任务?",
      Speanstyles: {  
        // color: "#1f1fa7",
        // "text-indent": 0
      },
      Buttonstyle: {
        background: '#BF3434'
      },
      Buttonname: "确定",
    })
    function FinishSimulationTasks(fn) {
      if (fn === 'Cancel') {
        FinishDialogComponent.Dialogboolean = false
      }
      if (fn === 'Ready') {
        postData("/api/TrainingTask/Finish", JSON.stringify({ id: State.SimulationtaskId }), sessionStorage.getItem("token")).
          then(function (res) {
            if (res.result.success) {
              State.taskaInformation.taskState = "已结束"
              FinishDialogComponent.Dialogboolean = false
            }
          })
          .catch((error) => {
            console.log(error)
          });
      }
    }
    //发布实训任务
    function ReleaseDialog() {
      ReleaseDialogComponent.Dialogboolean = true
    }
    //发布实训数据
    let ReleaseDialogComponent = reactive({
      Dialogboolean: false,
      Msg: "是否发布此实训任务?",
      Speanstyles: {

      },
      Buttonstyle: {
        background: 'linear-gradient(-90deg, #0974d8, #3d8ef1, #7c7ff8)'
      },
      Buttonname: "确定",
    })
    function ReleaseSimulationTasks(fn) {
      if (fn === 'Cancel') {
        ReleaseDialogComponent.Dialogboolean = false
      }
      if (fn === 'Ready') {
        postData("/api/TrainingTask/Release", JSON.stringify({ id: State.SimulationtaskId }), sessionStorage.getItem("token")).
          then(function (res) {
            if (res.result.success) {
              State.taskaInformation.taskState = "进行中"
              ReleaseDialogComponent.Dialogboolean = false
            }
          })
          .catch((error) => {
            console.log(error)
          });
      }
    }
    //删除实训任务
    function DeleteDialog() {
      DeleteDialogComponent.Dialogboolean = true
    }
    //删除实训任务数据
    let DeleteDialogComponent = reactive({
      Dialogboolean: false,
      Msg: "是否删除此实训任务?",
      Speanstyles: {

      },
      Buttonstyle: {
        background: '#BF3434'
      },
      Buttonname: "确定",
    })
    function DeleteSimulationTasks(fn) {
      if (fn === 'Cancel') {
        DeleteDialogComponent.Dialogboolean = false
      }
      if (fn === 'Ready') {
        ReleaseDialogComponent.Msg = "删除中，请耐心等待....."
        postData("/api/TrainingTask/Delete", JSON.stringify({ id: State.SimulationtaskId }), sessionStorage.getItem("token")).
          then(function (res) {
            if (res.result.success) {
              ReleaseDialogComponent.Msg = "删除成功"
              State.trainingtaskarr[State.SimulationtaskOneIndex].trainingTasks.splice(State.SimulationtaskTwoIndex, 1)
              // GetSimulationTasksValue(0)
              GetClassValue(State.SimulationtaskOneIndex)
              DeleteDialogComponent.Dialogboolean = false
              ReleaseDialogComponent.Msg = "是否删除此任务"
            }
          })
          .catch((error) => {
            console.log(error)
          });
      }
    }
    onMounted(() => {
    });
    return {
      State,
      classvalue,
      simulationtasksvalue,
      GetClassValue,
      GetSimulationTasksValue,
      dateFormat,
      FinishDialog,
      FinishDialogComponent,
      FinishSimulationTasks,
      ReleaseDialog,
      ReleaseDialogComponent,
      ReleaseSimulationTasks,
      DeleteDialog,
      DeleteDialogComponent,
      DeleteSimulationTasks,
      numFilter,
    };
  },
});
</script>
<style lang="less">
.Component-panel-span {
  text-indent: 0 !important;
}
.TaskPanel {
  position: absolute;
  width: 420px;
  height: calc(100% - 110px);
  left: 520px;
  top: 100px;
  border-radius: 16px;
  background: #ffffff;
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -o-user-select: none;
}

.TaskPanel .TaskPanel-title-img {
  position: absolute;
  left: 20px;
  top: 20px;
  width: auto;
  height: auto;
  max-height: 100%;
  max-height: 100%;
}

.TaskPanel .TaskPanel-title-name {
  position: absolute;
  left: 0px;
  top: 18px;
  width: 180px;
  height: 24px;
  font-size: 18px;
  color: #81859c;
  font-family: Source Han Sans CN;
  font-weight: 400;
  color: #81859c;
}

.TaskPanel .line {
  position: absolute;
  top: 190px;
  width: 420px;
  height: 1px;
  background: #eeeeee;
}

.TaskPanel .TaskPanel-option-one {
  position: absolute;
  left: 20px;
  top: 70px;
}

.TaskPanel .TaskPanel-option-two {
  position: absolute;
  left: 20px;
  top: 130px;
}

//设定下拉框的宽度
.TaskPanel .el-input__inner {
  width: 380px;
}

.TaskPanel-panel {
  position: absolute;
  display: flex;
  justify-content: flex-start;
  flex-direction: column;
  top: 200px;
  width: 100%;
  height: 100%;
}

.TaskPanel-panel>div {
  width: 100%;
  min-height: 50px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.TaskPanel-panel>div>span:nth-child(1) {
  padding-left: 30px;
  font-size: 16px;
  font-family: Source Han Sans CN;
  font-weight: 500;
  color: #81859c;
  text-align: center;
  user-select: none;
}

.TaskPanel-panel>div>span:nth-child(2) {
  padding-left: 20px;
  width: 1px;
  height: 12px;
  color: royalblue;
}

.TaskPanel-panel>div>span:nth-child(3) {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  padding-left: 20px;
  font-size: 16px;
  width: 250px;
  height: 14px;
  font-family: PingFang SC;
  font-weight: 500;
  color: #1b1b1d;
}

/* button按钮设置 */
.TaskPanel .TaskPanel-button {
  position: absolute;
  left: 40px;
  bottom: 30px;
  border-radius: 10px;
  width: 150px;
  height: 60px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.TaskPanel .button-open,
.TaskPanel .button-end {
  position: absolute;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  font-size: 18px;
  border-radius: 10px;
  border: 1px solid #fff;
  background-color: #E6E7EB;
  cursor: pointer;
}

.TaskPanel .button-end:hover {
  color: #fff;
  background-color: #BF3434;
}

.TaskPanel .button-open:hover {
  color: #fff;
  background: linear-gradient(-90deg, #0974d8, #3d8ef1, #7c7ff8);
  ;
}
</style>
